<template>
  <el-dialog
    v-model="dialogVisible"
    title="评论回复树"
    width="900px"
    :before-close="handleClose"
  >
    <div class="comment-tree">
      <!-- 根评论信息 -->
      <div v-if="rootComment" class="root-comment-section">
        <el-card class="root-comment-card">
          <div class="comment-header">
            <div class="user-info">
              <el-avatar
                :src="formatAvatarUrl(rootComment.userAvatar)"
                :size="40"
                fit="cover"
              >
                <template #default>
                  <IconifyIconOnline icon="ep:user" />
                </template>
              </el-avatar>
              <div class="user-details">
                <div class="user-name">
                  {{ rootComment.userNickName || rootComment.userName }}
                </div>
                <div class="comment-meta">
                  <span>{{ formatTime(rootComment.createTime) }}</span>
                  <span>IP: {{ rootComment.ipAddress }}</span>
                  <el-tag
                    :type="getStatusTagType(rootComment.status)"
                    size="small"
                  >
                    {{ getStatusText(rootComment.status) }}
                  </el-tag>
                </div>
              </div>
            </div>
            <div class="comment-actions">
              <el-button size="small" @click="handleViewDetail(rootComment)">
                详情
              </el-button>
            </div>
          </div>
          <div class="comment-content">
            <p>{{ rootComment.content }}</p>
            <div class="interaction-stats">
              <span class="like-count">👍 {{ rootComment.likeCount }}</span>
              <span class="reply-count">💬 {{ rootComment.replyCount }}</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 回复树 -->
      <div class="reply-tree-section">
        <div class="tree-header">
          <h4>回复列表 ({{ totalReplies }}条)</h4>
          <div class="tree-controls">
            <el-button size="small" @click="handleExpandAll">
              {{ allExpanded ? "收起全部" : "展开全部" }}
            </el-button>
            <el-button size="small" @click="handleRefreshTree">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>

        <div v-loading="loading" class="tree-content">
          <div v-if="commentTree.length === 0" class="empty-tree">
            <el-empty description="暂无回复" />
          </div>
          <div v-else class="tree-nodes">
            <CommentTreeNode
              v-for="comment in commentTree"
              :key="comment.id"
              :comment="comment"
              :level="1"
              :expanded="expandedNodes.has(comment.id)"
              @toggle-expand="handleToggleExpand"
              @view-detail="handleViewDetail"
              @delete="handleDelete"
              @ban-user="handleBanUser"
            />
          </div>
        </div>
      </div>

      <!-- 统计信息 -->
      <div class="tree-statistics">
        <el-row :gutter="16">
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ statistics.total }}</div>
              <div class="stat-label">总回复</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ statistics.pending }}</div>
              <div class="stat-label">待审核</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ statistics.approved }}</div>
              <div class="stat-label">已通过</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="stat-item">
              <div class="stat-number">{{ statistics.maxLevel }}</div>
              <div class="stat-label">最大层级</div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="primary" @click="handleExportTree">
          导出树结构
        </el-button>
      </div>
    </template>

    <!-- 评论详情对话框 -->
    <CommentDetail
      v-model:visible="showCommentDetail"
      :comment="currentComment"
      @refresh="handleRefreshTree"
    />

    <!-- 用户禁言对话框 -->
    <UserBanDialog
      v-model:visible="showUserBanDialog"
      :user-id="currentUserId"
      :comment="currentComment"
      @success="handleBanSuccess"
    />
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch, reactive } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Refresh } from "@element-plus/icons-vue";
import { IconifyIconOnline } from "@/components/ReIcon";
import {
  getCommentTreeApi,
  batchOperateCommentsApi,
  deleteCommentApi,
  markSensitiveCommentApi,
  unmarkSensitiveCommentApi,
  type CommentInfo,
  CommentManagementUtils
} from "@/api/comment-management";
import CommentTreeNode from "./CommentTreeNode.vue";
import CommentDetail from "./CommentDetail.vue";
import UserBanDialog from "./UserBanDialog.vue";

// Props
interface Props {
  visible: boolean;
  rootComment: CommentInfo | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  rootComment: null
});

// Emits
const emit = defineEmits<{
  "update:visible": [value: boolean];
  refresh: [];
}>();

// 响应式数据
const dialogVisible = computed({
  get: () => props.visible,
  set: value => emit("update:visible", value)
});

const loading = ref(false);
const commentTree = ref<CommentInfo[]>([]);
const expandedNodes = ref(new Set<number>());
const allExpanded = ref(false);
const currentComment = ref<CommentInfo | null>(null);
const currentUserId = ref<number>(0);

// 对话框状态
const showCommentDetail = ref(false);
const showUserBanDialog = ref(false);

// 统计信息
const statistics = reactive({
  total: 0,
  pending: 0,
  approved: 0,
  maxLevel: 0
});

// 计算属性
const totalReplies = computed(() => {
  return countTotalComments(commentTree.value);
});

// 监听props变化
watch(
  () => props.visible,
  visible => {
    if (visible && props.rootComment) {
      loadCommentTree();
    }
  }
);

// 方法
const loadCommentTree = async () => {
  if (!props.rootComment) return;

  loading.value = true;
  try {
    const data = await getCommentTreeApi(
      props.rootComment.articleId,
      props.rootComment.id
    );

    if (data && data.code === 200) {
      commentTree.value = data.data || [];
      calculateStatistics();
    } else {
      ElMessage.error(data?.message || "加载评论树失败");
    }
  } catch (error) {
    console.error("加载评论树失败:", error);
    ElMessage.error("加载评论树失败");
  } finally {
    loading.value = false;
  }
};

const calculateStatistics = () => {
  const allComments = flattenCommentTree(commentTree.value);
  statistics.total = allComments.length;
  statistics.pending = allComments.filter(c => c.status === 0).length;
  statistics.approved = allComments.filter(c => c.status === 1).length;
  statistics.maxLevel = Math.max(...allComments.map(c => c.level), 0);
};

const countTotalComments = (comments: CommentInfo[]): number => {
  let count = 0;
  for (const comment of comments) {
    count += 1;
    if (comment.children && comment.children.length > 0) {
      count += countTotalComments(comment.children);
    }
  }
  return count;
};

const flattenCommentTree = (comments: CommentInfo[]): CommentInfo[] => {
  const result: CommentInfo[] = [];
  for (const comment of comments) {
    result.push(comment);
    if (comment.children && comment.children.length > 0) {
      result.push(...flattenCommentTree(comment.children));
    }
  }
  return result;
};

const handleToggleExpand = (commentId: number) => {
  if (expandedNodes.value.has(commentId)) {
    expandedNodes.value.delete(commentId);
  } else {
    expandedNodes.value.add(commentId);
  }
};

const handleExpandAll = () => {
  if (allExpanded.value) {
    expandedNodes.value.clear();
    allExpanded.value = false;
  } else {
    const allComments = flattenCommentTree(commentTree.value);
    allComments.forEach(comment => {
      if (comment.children && comment.children.length > 0) {
        expandedNodes.value.add(comment.id);
      }
    });
    allExpanded.value = true;
  }
};

const handleRefreshTree = () => {
  loadCommentTree();
  emit("refresh");
};

const handleViewDetail = (comment: CommentInfo) => {
  currentComment.value = comment;
  showCommentDetail.value = true;
};

const handleDelete = async (comment: CommentInfo) => {
  try {
    await ElMessageBox.confirm(
      "确定要删除这条评论吗？删除后可以恢复。",
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const data = await batchOperateCommentsApi({
      commentIds: [comment.id],
      operationType: "DELETE",
      remark: "管理员删除",
      sendNotification: true
    });

    if (data && data.code === 200) {
      ElMessage.success("删除评论成功");
      handleRefreshTree();
    } else {
      ElMessage.error(data?.message || "删除评论失败");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除评论失败:", error);
      ElMessage.error("删除评论失败");
    }
  }
};

const handleBanUser = (comment: CommentInfo) => {
  currentComment.value = comment;
  currentUserId.value = comment.userId;
  showUserBanDialog.value = true;
};

const handleBanSuccess = () => {
  ElMessage.success("用户禁言成功");
  showUserBanDialog.value = false;
  handleRefreshTree();
};

const handleExportTree = () => {
  if (!props.rootComment) return;

  const exportData = {
    rootComment: props.rootComment,
    replyTree: commentTree.value,
    statistics: statistics,
    exportTime: new Date().toLocaleString()
  };

  const blob = new Blob([JSON.stringify(exportData, null, 2)], {
    type: "application/json"
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `评论树_${props.rootComment.id}_${Date.now()}.json`;
  a.click();
  URL.revokeObjectURL(url);

  ElMessage.success("导出成功");
};

const handleClose = () => {
  dialogVisible.value = false;
  // 清理数据
  setTimeout(() => {
    commentTree.value = [];
    expandedNodes.value.clear();
    allExpanded.value = false;
    currentComment.value = null;
    currentUserId.value = 0;
    Object.assign(statistics, {
      total: 0,
      pending: 0,
      approved: 0,
      maxLevel: 0
    });
  }, 300);
};

// 工具方法
const getStatusText = (status: number) => {
  return CommentManagementUtils.getStatusText(status);
};

const getStatusTagType = (status: number) => {
  return CommentManagementUtils.getStatusTagType(status);
};

const formatTime = (time: string) => {
  return CommentManagementUtils.formatTime(time);
};

// 格式化头像URL
const formatAvatarUrl = (url: string): string => {
  if (!url) return "";

  // 如果已经是完整URL，直接返回
  if (url.startsWith("http://") || url.startsWith("https://")) {
    return url;
  }

  // 如果是相对路径，添加基础URL
  const baseURL = import.meta.env.DEV
    ? "http://localhost:8081"
    : "http://localhost:8081";
  return baseURL + url;
};
</script>

<style scoped lang="scss">
.comment-tree {
  .root-comment-section {
    margin-bottom: 20px;

    .root-comment-card {
      border-left: 4px solid #409eff;

      .comment-header {
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        margin-bottom: 12px;

        .user-info {
          display: flex;
          gap: 12px;
          align-items: center;

          .user-details {
            .user-name {
              margin-bottom: 4px;
              font-weight: 600;
              color: #303133;
            }

            .comment-meta {
              display: flex;
              gap: 12px;
              align-items: center;
              font-size: 12px;
              color: #909399;
            }
          }
        }
      }

      .comment-content {
        p {
          margin: 0 0 12px;
          line-height: 1.6;
          word-break: break-word;
        }

        .interaction-stats {
          display: flex;
          gap: 16px;
          font-size: 14px;
          color: #606266;
        }
      }
    }
  }

  .reply-tree-section {
    margin-bottom: 20px;

    .tree-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 16px;

      h4 {
        margin: 0;
        color: #303133;
      }

      .tree-controls {
        display: flex;
        gap: 8px;
      }
    }

    .tree-content {
      min-height: 200px;

      .empty-tree {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 200px;
      }

      .tree-nodes {
        padding-left: 16px;
        border-left: 2px solid #f0f0f0;
      }
    }
  }

  .tree-statistics {
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;

    .stat-item {
      text-align: center;

      .stat-number {
        margin-bottom: 4px;
        font-size: 24px;
        font-weight: bold;
        color: #409eff;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}
</style>
